#import "ALEventColumnEntry.h"
#import "ALElementColumnEntry.h"
#import "NSObject+BlockObservation.h"
#import "ALEventView.h"


@interface ALEventColumnEntry (ALEventColumnEntryPrivateMethods)
-(ALEventView *)eventView_;
@end


#pragma mark -
@implementation ALEventColumnEntry

-(void)columnEntryWasAddedToColumnView {
	[super columnEntryWasAddedToColumnView];
	[self setAutomaticallyRearrangesObjects:YES];
	AMBlockTask selectedTask = ^(id object, NSDictionary *change) {
		[[self eventView_] setSelected:[self selected]];
	};
	[self addObserverForKeyPath:ALSelectedKey task:selectedTask];
}

-(void)columnEntryDidBeginEditingAtPoint:(NSPoint)clickPoint {
	[super columnEntryDidBeginEditingAtPoint:clickPoint];
	if ([[self childEntries] count] == 0)
		return;
	for (NSUInteger elementIndex = 0; elementIndex < [[self childEntries] count]; elementIndex++) {
		ALElementColumnEntry *currentElement = [[self childEntries] objectAtIndex:elementIndex];
		// TODO: SHOULD WE BE PASSING THE CLICK POINT (ACCOUNTING FOR COORDINAT CONVERSION) TO THE ELEMENT?
		[currentElement columnEntryDidBeginEditingAtPoint:NSZeroPoint];
		NSView *currentValueView = [currentElement valueView];
		if (currentElement == [[self childEntries] lastObject]) {
			[currentValueView setNextKeyView:[self columnView]];
			continue;
		}
		
		ALElementColumnEntry *nextElement = [[self childEntries] objectAtIndex:elementIndex + 1];
		NSView *nextValueView = [nextElement valueView];
		[currentValueView setNextKeyView:nextValueView];
	}
	NSPoint superPoint = [[self view] convertPoint:clickPoint toView:[[self view] superview]];
	NSView *deepestView = [[self view] hitTest:superPoint];
	ALElementColumnEntry *closestEntry = (ALElementColumnEntry *)[[self columnView] entryWithView:deepestView];
	if (!closestEntry || ![closestEntry isKindOfClass:[ALElementColumnEntry class]]) 
		closestEntry = [[self childEntries] objectAtIndex:0];
	NSView *closestValueView = [closestEntry valueView];
	[[closestValueView window] makeFirstResponder:closestValueView];
}

-(void)columnEntryDidEndEditing {
	for (SMRColumnEntry *entry in [self childEntries])
		[entry columnEntryDidEndEditing];
}

-(ALEventView *)eventView_ {
	if ([[self view] isKindOfClass:[ALEventView class]])
		return (ALEventView *)[self view];
	return nil;
}

@end
